const express = require('express')
const router = express.Router()
const pool = require('../../db/db')
const Response = require("../../utils/ResponseData")

/**
 * 新增宠物接口
 * 请求url：http://localhost:3001/pet/add
 */
router.post("/add", (req, res, next) => {
    // 获取前端请求信息
    let { pImg, pName, pYear, pGender, pType, pContent, pBreed } = req?.body
    let { uid } = req?.user
    // 编写sql
    const sql = "insert into pet(p_img,p_name,p_year,p_gender,p_type,p_content,p_breed,user_id) value (?,?,?,?,?,?,?,?)"
    // 执行sql
    pool.query(sql, [pImg, pName, pYear, pGender, pType, pContent, pBreed, uid], (err, result) => {
        if (err) {
            console.log("Pet.js=>/pet/add接口：", err)
            next(err)
            return
        }
        if (result.affectedRows > 0) {
            res.send(Response.success(result, "宠物添加成功！"))
        } else {
            res.send(Response.error("宠物添加失败！"))
        }
    })
})

// 宠物列表获取
router.get("/getAll", (req, res, next) => {
    let { uid } = req?.user
    const sql = "select * from pet where user_id =?"
    pool.querySync(sql, [uid])
        .then(result => {
            if (result.length > 0) {
                res.send(Response.success(result, "宠物列表数据获取成功！"))
            } else {
                res.send(Response.error("宠物列表信息获取失败！"))
            }
        }).catch(err => {
            if (err) {
                console.log("Pet.js=>/pet/getAll接口：", err)
                next(err)
                return
            }
        })
})
module.exports = router